import time


class Mole:
    """Mole entity tracking appearance time, type and hit state.

    mole_type: one of 'normal', 'pink', 'black', 'gold'
    After being hit, the mole stays visible for a short hit animation duration
    so the game can show closed eyes / tongue effects.
    """

    HIT_DISPLAY_MS = 400

    def __init__(self, up_ms: int, mole_type: str = 'normal'):
        self.up_ms = up_ms
        self.spawn_time = self._now_ms()
        self.hit_flag = False
        self.hit_time = None
        # mole type determines behavior on hit
        self.mole_type = mole_type
        # 新增暂停相关属性
        self.paused = False
        self.pause_start = None
        self.pause_total = 0  # 总暂停时间

    def _now_ms(self):
        return int(time.time() * 1000)

    def elapsed(self) -> int:
        if self.paused:
            # 如果当前正在暂停，使用暂停开始时间计算
            return self.pause_start - self.spawn_time - self.pause_total
        # 否则从总时间中减去累计的暂停时间
        return self._now_ms() - self.spawn_time - self.pause_total

    def is_alive(self) -> bool:
        # alive while not expired (including brief hit display)
        return not self.is_expired()

    def is_expired(self) -> bool:
        now = self._now_ms()
        if self.hit_flag:
            if self.hit_time is None:
                return False
            # 计算实际经过的时间（减去暂停时间）
            hit_elapsed = now - self.hit_time
            if self.paused:
                hit_elapsed = self.pause_start - self.hit_time
            return hit_elapsed >= self.HIT_DISPLAY_MS
        # 计算实际经过的时间（减去暂停时间）
        elapsed = now - self.spawn_time - self.pause_total
        if self.paused:
            elapsed = self.pause_start - self.spawn_time - self.pause_total
        return elapsed >= self.up_ms

    def hit(self):
        if not self.hit_flag:
            self.hit_flag = True
            self.hit_time = self._now_ms()
            return True
        return False
    
    def pause(self):
        """暂停地鼠的计时器"""
        if not self.paused:
            self.paused = True
            self.pause_start = self._now_ms()
            
    def resume(self):
        """恢复地鼠的计时器"""
        if self.paused:
            self.paused = False
            # 累计暂停的时间
            self.pause_total += self._now_ms() - self.pause_start
            self.pause_start = None
